import com.fasterxml.jackson.annotation.JsonIgnore;
import com.freestyle.common.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by rocklee on 2022/2/5 14:33
 */
@NoArgsConstructor
@AllArgsConstructor
public class ResponseEntity<T> implements Serializable {
  private long id;
  private int errCode;
  private String message;
  private T result;
  private Map<String,Object> ext=new LinkedHashMap<>();
  public static <V> ResponseEntity<V> fromResult(long id, V val){
    ResponseEntity<V> ret = new ResponseEntity<>();
    ret.result = val;
    ret.id=id;
    return ret;
  }
  public static <T>ResponseEntity<T> fromErr(long id, int errCode, String message){
    ResponseEntity<T> ret=new ResponseEntity<T>(id,errCode,message,(T)null,new LinkedHashMap<>());
    return ret;
  }
  public static ResponseEntity fromErr(long id, Throwable ex){
    ResponseEntity ret=new ResponseEntity(id,-1,ex.getMessage(),null,new LinkedHashMap<>());
    ret.ext.put("ex",ex);
    return ret;
  }
  @JsonIgnore
  public Throwable getThrowable(){
    return (Throwable) ext.get("ex");
  }
  @JsonIgnore
  public Map toMap(){
      Map map= JsonUtils.fromJson(JsonUtils.toJsonString(this), HashMap.class);
      return map;
  }
  public ResponseEntity(Exception pvException, Exception pvException2){
    this(pvException==null?pvException2:pvException);
  }
  public ResponseEntity(Exception pvException){
    errCode=-1;
    result=null;
    message=pvException.getMessage();
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public int getErrCode() {
    return errCode;
  }

  public void setErrCode(int errCode) {
    this.errCode = errCode;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public T getResult() {
    return result;
  }

  public void setResult(T result) {
    this.result = result;
  }

  public Map<String, Object> getExt() {
    return ext;
  }

  public void setExt(Map<String, Object> extMap) {
    this.ext = extMap;
  }
  public void put(String key,Object value){
    if (this.ext==null){
      this.ext=new LinkedHashMap<>();
    }
    this.ext.put(key,value);
  }
  @JsonIgnore
  public <T> T get(String key){
     if (this.ext==null)return null;
     return (T) this.ext.get(key);
  }
}
